package com.example.design.ddd.practice.adapter.driven.persistence.orgmng;

import com.example.design.ddd.practice.domain.orgmng.entity.Org;
import com.example.design.ddd.practice.domain.orgmng.repository.OrgRepository;
import com.example.design.ddd.practice.domain.orgmng.entity.OrgStatus;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * @Description
 * @Author liuzhihui
 * @Date 2024/5/31
 */
@Repository
public class OrgRepositoryJdbc implements OrgRepository {
    JdbcTemplate jdbc;
    SimpleJdbcInsert insertOrg;

    public Org save(Org org) {
        return null;
    }

    @Override
    public Optional findByIdAndStatus(long tenantId, Long id, OrgStatus status) {
        return null;
    }

    @Override
    public int countBySuperiorAndName(long tenantId, Long superiorId, String name) {
        return 0;
    }

    @Override
    public boolean existsBySuperiorAndName(Long tenant, Long superior, String name) {
        return false;
    }

    @Override
    public Boolean existsByIdAndStatus(Long tenantId, Long orgId, OrgStatus orgStatus) {
        return true;
    }

    @Override
    public Optional<Org> findById(Long tenantId, Long id) {
        return Optional.empty();
    }

    @Override
    public boolean existsBySuperiorIdAndName(Long tenantId, Long superiorId, String name) {
        final String sql = " select 1 from org "
                + " where tenant_id = ?  and superior_id = ? and name = ?"
                + " limit 1 ";

        try {
            return jdbc.queryForObject(sql, Integer.class, tenantId, superiorId, name) != null;
        } catch (IncorrectResultSizeDataAccessException e) {
            return false;
        }
    }

    @Override
    public int update(Org org) {
        String sql = "update org "
                + " set superior_id = ? "
                + ", org_type_code =? "
                + ", leader_id = ?"
                + ", name = ?"
                + ", status_code =?"
                + ", last_updated_at = ?"
                + ", last_updated_by = ? "
                + " where tenant_id = ? and id = ? ";

        return this.jdbc.update(sql
                , org.getSuperiorId()
                , org.getOrgTypeCode()
                , org.getLeaderId()
                , org.getName()
                , org.getStatus().getKey()
                , org.getLastUpdatedAt()
                , org.getLastUpdatedBy()
                , org.getTenantId()
                , org.getId()
        );
    }

}